<template>
  <div class="cms-media-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>媒体库</span>
          <el-button type="primary" @click="handleUpload">
            <el-icon><Upload /></el-icon>
            上传文件
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="filter-box">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="文件名">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入文件名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="文件类型">
            <el-select 
              v-model="searchForm.type" 
              placeholder="请选择类型"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="图片" value="image" />
              <el-option label="视频" value="video" />
              <el-option label="音频" value="audio" />
              <el-option label="文档" value="document" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 视图切换 -->
        <el-radio-group v-model="viewMode" size="default">
          <el-radio-button value="grid">
            <el-icon><Grid /></el-icon>
            网格视图
          </el-radio-button>
          <el-radio-button value="list">
            <el-icon><List /></el-icon>
            列表视图
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 批量操作 -->
      <div class="toolbar">
        <el-button 
          type="danger" 
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-text type="info">
          已选择 {{ selectedIds.length }} 个文件，共 {{ pagination.total }} 个
        </el-text>
      </div>

      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="media-grid">
        <div
          v-for="item in tableData"
          :key="item.id"
          class="media-item"
          :class="{ selected: selectedIds.includes(item.id) }"
          @click="handleSelect(item)"
        >
          <div class="media-preview">
            <img 
              v-if="item.type === 'image'" 
              :src="item.url" 
              :alt="item.name" 
            />
            <el-icon v-else :size="60" :color="getTypeColor(item.type)">
              <component :is="getTypeIcon(item.type)" />
            </el-icon>
          </div>
          <div class="media-info">
            <el-text class="media-name" truncated>{{ item.name }}</el-text>
            <el-text size="small" type="info">{{ item.size }}</el-text>
          </div>
          <div class="media-actions">
            <el-button 
              type="primary" 
              size="small" 
              link
              @click.stop="handleView(item)"
            >
              查看
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              link
              @click.stop="handleDelete(item)"
            >
              删除
            </el-button>
          </div>
          <el-checkbox 
            v-model="selectedIds" 
            :value="item.id" 
            class="media-checkbox"
            @click.stop
          />
        </div>
      </div>

      <!-- 列表视图 -->
      <el-table 
        v-else
        :data="tableData" 
        border 
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="预览" width="100" align="center">
          <template #default="{ row }">
            <img 
              v-if="row.type === 'image'" 
              :src="row.url" 
              class="table-preview" 
            />
            <el-icon v-else :size="40" :color="getTypeColor(row.type)">
              <component :is="getTypeIcon(row.type)" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="文件名" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag>{{ getTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="100" align="center" />
        <el-table-column prop="uploadUser" label="上传者" width="120" />
        <el-table-column prop="uploadTime" label="上传时间" width="180" sortable />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleView(row)"
            >
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleCopy(row)"
            >
              <el-icon><DocumentCopy /></el-icon>
              复制链接
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              link
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[12, 24, 48, 96]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      width="600px"
    >
      <el-upload
        drag
        action="#"
        multiple
        :auto-upload="false"
        :on-change="handleFileChange"
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持jpg/png/gif/mp4/mp3/pdf等格式，单个文件不超过100MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUploadSubmit">
            开始上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Upload, Search, Refresh, Delete, Grid, List, View, DocumentCopy,
  Picture, VideoCamera, Headset, Document, Files
} from '@element-plus/icons-vue'

// 视图模式
const viewMode = ref('grid')

// 搜索表单
const searchForm = reactive({
  name: '',
  type: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedIds = ref([])

// 分页
const pagination = reactive({
  page: 1,
  size: 12,
  total: 0
})

// 上传对话框
const uploadDialogVisible = ref(false)
const uploadFiles = ref([])

// 获取类型图标
const getTypeIcon = (type) => {
  const iconMap = {
    image: Picture,
    video: VideoCamera,
    audio: Headset,
    document: Document,
    other: Files
  }
  return iconMap[type] || Files
}

// 获取类型颜色
const getTypeColor = (type) => {
  const colorMap = {
    image: '#67C23A',
    video: '#E6A23C',
    audio: '#409EFF',
    document: '#909399',
    other: '#C0C4CC'
  }
  return colorMap[type] || '#C0C4CC'
}

// 获取类型名称
const getTypeName = (type) => {
  const nameMap = {
    image: '图片',
    video: '视频',
    audio: '音频',
    document: '文档',
    other: '其他'
  }
  return nameMap[type] || type
}

// 查询
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.type = ''
  handleSearch()
}

// 选择文件
const handleSelect = (item) => {
  const index = selectedIds.value.indexOf(item.id)
  if (index > -1) {
    selectedIds.value.splice(index, 1)
  } else {
    selectedIds.value.push(item.id)
  }
}

// 查看
const handleView = (item) => {
  window.open(item.url, '_blank')
}

// 复制链接
const handleCopy = (item) => {
  navigator.clipboard.writeText(item.url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  })
}

// 删除
const handleDelete = (item) => {
  ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 个文件吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    loadData()
  }).catch(() => {})
}

// 上传文件
const handleUpload = () => {
  uploadFiles.value = []
  uploadDialogVisible.value = true
}

// 文件变化
const handleFileChange = (file) => {
  uploadFiles.value.push(file)
}

// 提交上传
const handleUploadSubmit = () => {
  if (uploadFiles.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  ElMessage.success('上传成功')
  uploadDialogVisible.value = false
  loadData()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页改变
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    tableData.value = [
      {
        id: 1,
        name: 'erp-banner.jpg',
        type: 'image',
        url: 'https://via.placeholder.com/300x200',
        size: '1.2 MB',
        uploadUser: '张三',
        uploadTime: '2024-10-15 10:30:00'
      },
      {
        id: 2,
        name: 'product-intro.mp4',
        type: 'video',
        url: '#',
        size: '45.8 MB',
        uploadUser: '李四',
        uploadTime: '2024-10-14 14:20:00'
      },
      {
        id: 3,
        name: 'background-music.mp3',
        type: 'audio',
        url: '#',
        size: '3.5 MB',
        uploadUser: '王五',
        uploadTime: '2024-10-13 09:00:00'
      },
      {
        id: 4,
        name: 'user-manual.pdf',
        type: 'document',
        url: '#',
        size: '8.2 MB',
        uploadUser: '赵六',
        uploadTime: '2024-10-12 16:45:00'
      }
    ]
    
    pagination.total = tableData.value.length
  } catch (error) {
    ElMessage.error('加载数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.cms-media-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-box {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.media-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.media-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.media-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.media-item.selected {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
}

.media-preview {
  width: 100%;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.media-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.media-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin-bottom: 10px;
}

.media-name {
  font-size: 14px;
  font-weight: 500;
}

.media-actions {
  display: flex;
  justify-content: space-around;
}

.media-checkbox {
  position: absolute;
  top: 10px;
  right: 10px;
}

.table-preview {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

